package com.hzpd.hainan.module.usercenter.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hzpd.hainan.R;
import com.hzpd.hainan.app.BaseFragment;
import com.hzpd.hainan.config.CODE;
import com.hzpd.hainan.custorm.CustomProgressDialog;
import com.hzpd.hainan.model.usercenter.UserEntity;
import com.hzpd.hainan.module.usercenter.UserCenterFragment;
import com.hzpd.hainan.module.usercenter.acticity.AgreementActivity;
import com.hzpd.hainan.module.usercenter.acticity.LoginActivity;
import com.hzpd.hainan.net.Factory;
import com.hzpd.hainan.utils.AAnim;
import com.hzpd.hainan.utils.DeviceUtils;
import com.hzpd.hainan.utils.LogUtils;
import com.hzpd.hainan.utils.ParamUtils;
import com.hzpd.hainan.utils.TUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/7/5.
 */

public class RegisterFragment extends BaseFragment {
    private static final String TAG = "RegisterFragment";
    @BindView(R.id.title_stilte_layout)
    TextView title_stilte_layout;
    @BindView(R.id.account_et_register_fragment)
    EditText account_et_register_fragment;//手机号
    @BindView(R.id.code_et_register_fragment)
    EditText code_et_register_fragment;
    @BindView(R.id.code_tv_registre_fragment)
    TextView code_tv_registre_fragment;
    @BindView(R.id.pw_et_register_fragment)
    EditText pw_et_register_fragment;
    @BindView(R.id.btn_register_fragment)
    Button btn_register_fragment;
    private CustomProgressDialog dialog;

    int t=120;
    private Timer timer;
    private String phoneNumber;
    private String pw;


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (333 == msg.what) {
                try {
                    code_tv_registre_fragment.setText(t + "秒");
                    t--;
                    if (t < 0) {
                        resetTimer();
                    }
                    disMissDialog();
                }catch (Exception e){
                    e.printStackTrace();
                }

            } else if (444 == msg.what) { //验证成功
                disMissDialog();
                LogUtils.i("验证成功");
                TUtils.toast("验证成功");
                submitregister();
            } else if (555 == msg.what) {  //验证失败
                code_et_register_fragment.setText("");
                btn_register_fragment.setEnabled(true);

                disMissDialog();
                TUtils.toast("验证失败");
                resetTimer();
            } else if (445 == msg.what) { //验证码获取成功
                disMissDialog();
                TUtils.toast("验证码获取成功");
                startTime();

            } else if (446 == msg.what) {
                disMissDialog();
                TUtils.toast("获取验证码失败");

                resetTimer();

            }
        }
    };
    @OnClick(R.id.code_tv_registre_fragment)
    public void getCode(View view){
        phoneNumber=account_et_register_fragment.getText().toString().trim();
        if (TextUtils.isEmpty(phoneNumber)){
            TUtils.toast("请输入手机号");
        }
        if (!TextUtils.isEmpty(phoneNumber)&&11==phoneNumber.length()){
            code_tv_registre_fragment.setClickable(false);
            showDialog();
            SMSSDK.getVerificationCode("86",phoneNumber);
            startTime();// 开启定时器

        }
    }
    @OnClick(R.id.btn_register_fragment)
    public void register(View view){

        phoneNumber=account_et_register_fragment.getText().toString().trim();
        String sms=code_et_register_fragment.getText().toString().trim();
        if (sms == null || "".equals(sms)) {
            TUtils.toast("验证码不能为空!");
            return;
        }

        final String pwd1 = pw_et_register_fragment.getText().toString();
        if (pwd1 == null || "".equals(pwd1)) {
            TUtils.toast("密码不能为空");
            return;
        }
        if (pwd1.length() < 6) {
            TUtils.toast("密码太短");
            return;
        }
        if (pwd1.length() > 12) {
            TUtils.toast("密码太长");
            return;
        }
        pw = pwd1;
//        btn_register_fragment.setEnabled(false);
        //TODO
        showDialog();
        LogUtils.e("phone->"+phoneNumber+"--sms-->"+sms);
        SMSSDK.submitVerificationCode("86", phoneNumber, sms);

        Log.e(TAG, "call: "+phoneNumber+pw);
//        submitregister();//写在这只为测试
    }

    private void startTime() {
        account_et_register_fragment.setEnabled(false);
        code_tv_registre_fragment.setClickable(false);
        code_tv_registre_fragment.setBackgroundResource(R.drawable.register_getsms_shape);
        if (timer!=null){
            timer.cancel();
        }
        timer=new Timer();
        TimerTask tt=new TimerTask() {
            @Override
            public void run() {
                handler.sendEmptyMessage(333);
            }
        };
        timer.schedule(tt,0,1000);
    }

    private void submitregister() {
        Map<String,String> map=new HashMap<>();
        map.put("mobile", phoneNumber);
        map.put("password", pw);
        map.put("device", DeviceUtils.getMyUUID(activity));
        Log.e(TAG, "call: "+phoneNumber+pw);
        Factory.provideHttpService().register(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()

                .subscribeOn(Schedulers.io())

                .filter(new Func1<UserEntity, Boolean>() {
                    @Override
                    public Boolean call(UserEntity userEntity) {
                        Log.e(TAG, "call: "+userEntity.code);
//                        if ("200".equals(userEntity.code)){
//                            return true;
//                        }else {
//                            TUtils.toast(userEntity.msg);
//
//                        }
                        return true;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<UserEntity>() {
                    @Override
                    public void call(UserEntity userEntity) {
                        LogUtils.e("register"+userEntity.code);
                        disMissDialog();
                        if ("200".equals(userEntity.code)) {
                            spu.setUser(userEntity.data);
                            Intent intent = new Intent();
                            intent.setAction(UserCenterFragment.ACTION_USER);
                            activity.sendBroadcast(intent);

                            TUtils.toast("注册成功");
                            activity.finish();

                        }else {
                            TUtils.toast(userEntity.msg);
                        }
                        ((LoginActivity) activity).finish();
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        Log.e(TAG, "call: "+throwable.getMessage());

                    }
                });

    }
    @OnClick(R.id.user_agreement_register_fragment)
    public void userAgree(View view){
        Intent intent=new Intent(getActivity(), AgreementActivity.class);
        startActivity(intent);
        AAnim.ActivityStartAnimation(getActivity());
    }




    private void resetTimer() {
        if (null==timer){
            return;
        }
        timer.cancel();
        code_tv_registre_fragment.setText("重新获取");
        code_tv_registre_fragment.setBackgroundResource(R.drawable.btn_login);
        account_et_register_fragment.setEnabled(true);
        btn_register_fragment.setEnabled(true);
        code_et_register_fragment.setEnabled(true);
        code_tv_registre_fragment.setClickable(true);
        btn_register_fragment.setClickable(true);
        account_et_register_fragment.setText("");
        code_et_register_fragment.setText("");
        pw_et_register_fragment.setText("");
        t=120;
    }

    @Override
    public int setMyContentView() {

        return R.layout.fragment_register;
    }

    @Override
    public void initView() {
        if (spu.getLanguage().equals(CODE.ZHONGWEN)) {
            title_stilte_layout.setText("注册");
            account_et_register_fragment.setHint("手机号");
            code_tv_registre_fragment.setText("发送短信");
            code_et_register_fragment.setHint("验证码");
            pw_et_register_fragment.setHint("密码");
            btn_register_fragment.setText("注册");
        }else{
            title_stilte_layout.setText("ཐོ་འགོད།");
            account_et_register_fragment.setHint("ཁ་པར་ཨང་གྲངས།");
            code_tv_registre_fragment.setText("བརྡ་འཕྲིན་སྐུར་བ།");
            code_et_register_fragment.setHint("ར་སྤྲོད་ཨང་གྲངས།");
            pw_et_register_fragment.setHint("གསང་གྲངས།");
            btn_register_fragment.setText("ཐོ་འགོད།");
        }
    }

    @Override
    public void initData() {

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        SMSSDK.registerEventHandler(new EventHandler(){
            @Override
            public void afterEvent(int event, int result, Object data) {
                LogUtils.e("registerEventHandler-->"+"event->"+event+",reselt->"+result);
                if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                    if(result==SMSSDK.RESULT_COMPLETE){
                        //验证码获取成功
                        handler.sendEmptyMessage(445);
                    }else if(result==SMSSDK.RESULT_ERROR){
                        handler.sendEmptyMessage(446);
                    }
                }else if(event==SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE){
                    if(result==SMSSDK.RESULT_COMPLETE){
                        handler.sendEmptyMessage(444);
                    }else if(result==SMSSDK.RESULT_ERROR){
                        handler.sendEmptyMessage(555);
                    }
                }
            }
        });
    }

    @OnClick(R.id.back_stitle_layout)
    public void goBack(View v) {
        if (null!=spu.getUser()) {
            // setResult(10);
            activity.finish();
        } else {
            activity.onBackPressed();
        }
    }
    @Override
    public void onDestroy() {
        if (timer!=null){
            timer.cancel();
        }
        handler.removeCallbacks(null);
        SMSSDK.unregisterAllEventHandler();
        super.onDestroy();

    }

    private void showDialog() {
        if (dialog == null){
            dialog = CustomProgressDialog.createDialog(activity, false);
        }
        dialog.show();
    }
    private void disMissDialog(){
        if (dialog != null){
            dialog.dismiss();
        }
    }
}
